package com.ruoyi.web.controller.task;


import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component("NodeTask")
public class NodeTask {
    @Autowired
    private  RestTemplate restTemplate;
    @Autowired
    private ISysDeptService iSysDeptService;
    // 使用Cron表达式，每10分钟执行
    @Scheduled(cron = "* 0/100 * * * ?")
    public void ryNoParams() {
//        if (iSysDeptService == null) {
//            throw new IllegalStateException("someService 未初始化");
//        }

        List<SysDept> sysDepts = iSysDeptService.selectDeptNodeList();

        for (SysDept sysDept : sysDepts) {
            if (sysDept.getDomain()!=null){
                String baseUrl = getBaseUrl(sysDept.getDomain());

                String  forObject=null;
                try {
                    System.out.println(baseUrl + "/heartbeat");
                     forObject = restTemplate.getForObject(baseUrl + "/dev-api/heartbeat", String.class);
                }catch (Exception e){

                }
                if (forObject==null){
                    sysDept.setStatus("1");
                    iSysDeptService.updateDept(sysDept);
                }else {
                    sysDept.setStatus("0");
                    iSysDeptService.updateDept(sysDept);
                    System.out.println(forObject);
                }
            }

        }
    }


    public static String getBaseUrl(String url) {
        return url.replaceAll("(http[s]?://[^/]+)(/.*)?", "$1");
    }


}
